package com.blacktea.behavioralpatterns.mediatorpattern;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: black tea
 * @date: 2023/3/25 16:36
 */
@Component
@Slf4j
public class ConcreteMediator implements Mediator {

    private final Map<String, Colleague> colleagueMap = new HashMap<>();

    @Override
    public void handleMessage(String message, Colleague colleague, Object... args) {
        if (colleague instanceof BookService) {
            // 图书服务发送消息
            if (message.equals("borrowBook")) {
                // 借书
                log.info("中介 图书服务借出图书...");
                // 更新图书库存
                Book book = (Book) args[0];
                UserService userService = (UserService) colleagueMap.get("userService");
                userService.updateBorrowInfo(book.getIsbn(), book.getBorrower());
            } else if (message.equals("returnBook")) {
                // 还书
                log.info("中介 图书服务收回图书...");
                // 更新图书库存
                Book book = (Book) args[0];
                UserService userService = (UserService) colleagueMap.get("userService");
                userService.updateBorrowInfo(book.getIsbn(), null);
            }
        } else if (colleague instanceof UserService) {
            // 用户服务发送消息
            if (message.equals("updateBorrowInfo")) {
                // 更新用户借阅信息
                log.info("中介 用户服务更新借阅信息...");
            }
        }
    }

    @Override
    public void register(String name, Colleague colleague) {
        colleagueMap.put(name, colleague);
    }
}
